package com.itheima.resolver;

import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ControllerExceptionResolver implements HandlerExceptionResolver {


    private String flag;

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        Result result = getResult(request);
        String resultStr = JSON.toJSON(result).toString();
        try {
            response.getWriter().write(resultStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ModelAndView();
    }

    private Result getResult(HttpServletRequest request) {
        String servletPath = request.getServletPath();
        String message = "未知错误";
        if (servletPath != null && servletPath.equals("/checkitem/add.do")) {
            message = MessageConstant.ADD_CHECKITEM_FAIL;
        }
        if (servletPath != null && servletPath.equals("/checkitem/delete.do")) {
            message = MessageConstant.DELETE_CHECKGROUP_FAIL;
        }
        if (servletPath != null && servletPath.equals("/checkitem/edit.do")) {
            message = MessageConstant.EDIT_CHECKITEM_FAIL;
        }
        if (servletPath != null && servletPath.equals("/checkitem/findById.do")) {
            message = MessageConstant.QUERY_CHECKITEM_FAIL;
        }
        if (servletPath != null && servletPath.equals("/checkitem/findAll.do")) {
            message = MessageConstant.QUERY_CHECKITEM_FAIL;
        }
        return new Result(false, message);
    }
}
